package top.hiai.Controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

import top.hiai.model.Session;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.jfplugin.mail.MailKit;

import top.hiai.config.BaseController;
import top.hiai.interceptor.LoginInterceptor;
import top.hiai.model.User;
import top.hiai.service.ArcTypeService;
import top.hiai.service.MessageService;
import top.hiai.service.UserService;
import top.hiai.service.UserXiaService;
import top.hiai.util.Md5Util;
import top.hiai.util.MyCaptchaRender;
import top.hiai.util.StringUtil;


/**
* @Author www.hiai.top
* @Email  goodsking@163.com
* @Message 更多资源尽在www.hiai.top,开发者：黄康权
* @Introduction 前台用户管理控制器
*/

public class UserController extends BaseController {

	int limtCountUser=10;		//用户个人中心每页的数量
	
	UserService userService = new UserService();
	ArcTypeService arcTypeService = new ArcTypeService();
	UserXiaService userXiaService = new UserXiaService();
	MessageService messageService = new MessageService();
	
	/**
	 * 渲染登录界面
	 */
	public void login(){
		setAttr("title", "用户登录");
		render("login.html");
	}
	/**
	 * 渲染注册界面
	 */
	public void regester(){
		setAttr("title", "用户注册");
		render("regester.html");
	}
	/**
	 * 渲染找回密码界面
	 */
	public void redmePassword(){
		setAttr("title", "找回密码");
		render("redmePassword.html");
	}
	/**
	 * 渲染用户个人中心主界面
	 */
	@Before(LoginInterceptor.class)
	public void userWelcome(){
		setAttr("title", "用户个人中心");
		User user = getSessionAttr("LoginUserCache");
    	int uid = user.getInt("uid");
    	setAttr("userMsg", userService.findById(uid));
		render("userWelcome.html");
	}
	/**
	 * 渲染用户发表文章界面
	 */
	@Before(LoginInterceptor.class)
	public void userArticleWrite(){
		setAttr("title", "发布文章页面");
		setAttr("arcTypeList", arcTypeService.getArcTypeList());
		//System.out.println("111");
		render("userArticleWrite.html");
	}
	/**
	 * 渲染用户文章管理界面
	 */
	@Before(LoginInterceptor.class)
	public void userArticleManage(){
		setAttr("title", "文章管理页面");
		render("userArticleManage.html");
	}
	/**
	 * 渲染用户评论管理界面
	 */
	@Before(LoginInterceptor.class)
	public void userCommentManage(){
		setAttr("title", "评论管理页面");
		render("userCommentManage.html");
	}
	/**
	 * 渲染用户已经下载的资源界面
	 */
	@Before(LoginInterceptor.class)
	public void userArticleDownload(){
		setAttr("title", "用户已经下载资源页面");
		User user = getSessionAttr("LoginUserCache");
    	int uid = user.getInt("uid");
    	setAttr("xiaList", userXiaService.paginateGetUserXia(getParaToInt("p", 1),limtCountUser, uid));
    	render("userArticleDownload.html");
	}
	/**
	 * 渲染用户界面中的系统消息界面
	 */
	@Before(LoginInterceptor.class)
	public void userSystemMessage(){
		setAttr("title", "用户已经下载资源页面");
		User user = getSessionAttr("LoginUserCache");
    	int uid = user.getInt("uid");
    	setAttr("MessageList", messageService.paginateGetMessage(getParaToInt("p", 1),limtCountUser, uid));
		render("userSystemMessage.html");
		//renderJson();
	}
	/**
	 * 渲染用户修改个人信息界面
	 */
	@Before(LoginInterceptor.class)
	public void userSetPersonal(){
		setAttr("title", "修改个人信息");
		User user = getSessionAttr("LoginUserCache");
		int uid = user.getInt("uid");
		setAttr("userMsg", userService.findById(uid));
		setSessionAttr("LoginUserCache",userService.findById(uid));
		render("userSetPersonal.html");
		//renderJson();
	}
    /**
     * 个人中心修改用户的信息
     * 包括修改，用户昵称，用户性别，用户个人签名
     */
	@Before(LoginInterceptor.class)
    public void userSetData(){
    	getModel(User.class).update();
    	redirect("/user/userSetPersonal");
    }
    /**
     * 个人中心修改用户密码
     * @throws UnsupportedEncodingException 
     * @throws NoSuchAlgorithmException 
     */
	@Before(LoginInterceptor.class)
	public void userSetPassword() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		int uid = getParaToInt("user.uid");
		String password = getPara("oldPassword");
		String newPassword = getPara("newPassword");
		Ret ret = userService.updatePassword(uid , password , newPassword);
		renderJson(ret);
		
	}
	/**
	 * 个人中心用户修改用户的头像
	 */
	public void uploadAvatar(){
		//int uid = getParaToInt("user.uid");
		User user = getSessionAttr("LoginUserCache");
		int uid = user.getInt("uid");
		
		UploadFile uf = null;
		try {
			uf = getFile("avatar", userService.getAvatarTempDir(), userService.getAvatarMaxSize());
			if (uf == null) {
				renderJson(Ret.fail("msg", "请先选择上传文件"));
				return;
			}
		} catch (Exception e) {
			if (e instanceof com.jfinal.upload.ExceededSizeException) {
				renderJson(Ret.fail("msg", "文件大小超出范围"));
			} else {
				if (uf != null) {
					// 只有出现异常时才能删除，不能在 finally 中删，因为后面需要用到上传文件
					uf.getFile().delete();
				}
				renderJson(Ret.fail("msg", e.getMessage()));
			}
			return ;
		}

		Ret ret = userService.uploadAvatar(uid, uf);
		if (ret.isOk()) {   // 上传成功则将文件 url 径暂存起来，供下个环节进行裁切
			setSessionAttr("avatarUrl", ret.get("avatarUrl"));
		}
		renderJson(ret);
	}
	/**
	 * 保存 jcrop 裁切区域为用户头像
	 */
	public void saveAvatar() {
		String avatarUrl = getSessionAttr("avatarUrl");
		User user = getSessionAttr("LoginUserCache");
		int x = getParaToInt("x");
		int y = getParaToInt("y");
		int width = getParaToInt("width");
		int height = getParaToInt("height");
		Ret ret = userService.saveAvatar(user, avatarUrl, x, y, width, height);
		renderJson(ret);
	}
	
	/**
	 * 前台根据用户的邮箱验证用户登录，这里修改了不用验证码登录
	 */
	@SuppressWarnings("static-access")
	public void loginVerification(){
		setAttr("title", "用户登录");
		User userLoginManage ;
		//获取用户输入的账号和密码
    	String email  = getPara("email");
    	String password = getPara("password");
 	
    	//把密码进行Md5加密
    	try {
			password = Md5Util.EncoderPwdByMd5(password);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	//验证验证码的正确
    	//boolean validate = validateCaptcha("imageCode");
    	//首先验证验证码的正确性
    	//if(validate){
    		//从数据库中获取数据
    		userLoginManage = userService.findUserByNameAndPassword(email);
        	//验证用户名和密码是否正确
        	if(userLoginManage != null){
        		if("false".equals(userLoginManage.getStr("is_off"))){	//验证用户是否被禁用了
        			//System.out.println(userLoginManage);
        			//System.out.println("面膜："+userLoginManage.getStr("password"));
        			if(password.equals(userLoginManage.getStr("password"))){	//验证密码的正确性
        				// 将用户信息保存到缓存，用作超时判断
        				//userLoginManage.removeSensitiveInfo();  //移除密码

        				userLoginManage.removeSensitiveInfo();
        				long liveSeconds =  120 * 60;
        				long expireAt = System.currentTimeMillis() + (liveSeconds * 1000);
        				Session session = new Session();
        				String sessionId = StrKit.getRandomUUID();
        				
        				session.setId(sessionId);
        				session.setAccountId(userLoginManage.getUid());
        				session.setExpireAt(expireAt);
        				CacheKit.put(userService.loginAccountCacheName, sessionId, userLoginManage);
        				
        				String sessionIds = userLoginManage.getStr(userService.sessionIdName);
        				setCookie(userService.sessionIdName, sessionId, -1, true);
        				setAttr(userService.loginAccountCacheName, userLoginManage.get(userService.loginAccountCacheName));
        				
        				setSessionAttr("LoginUserCache",userLoginManage);
        				//setSessionUser(user); // 设置session
        				//System.out.println(getSessionAttr("LoginUserCache"));
        				
        				redirect("/user/userWelcome");
        			}else{
                    	setAttr("errorMsg", "邮箱或密码输入错误，请重新输入。");
                        render("login.html");
                        return;
        			}
        		}else{
                	setAttr("errorMsg", "对不起该用户被禁用了，请联系管理员解除。");
                    render("login.html");
                    return;
        		}	
        	}else{
            	setAttr("errorMsg", "该邮箱不存在,请重新输入。");
                render("login.html");
                return;
        	}
//    	}else{
//        	setAttr("errorMsg", "验证码输入错误,请重新输入。");
//            render("login.html");
//            return;
//    	}
	}
	/**
	 * 用户注册验证
	 */
	@SuppressWarnings("null")
	public void regesterCheck(){
		setAttr("title", "用户注册");
		User userRegesterManage = new User();
    	String email  = getPara("user.email");
    	String username  = getPara("user.username");
    	String password = getPara("user.password");
    	String newPassword = getPara("newPassword");
    	//String imageCode = getPara("imageCode");
    	
    	//注册时间
    	Date register_date = new Date();
    	
    	if(password.equals(newPassword)){		//判断两次密码是否一致
        	//imageCode.toUpperCase();
        	//boolean validate = MyCaptchaRender.validate(this, imageCode);
    		//if(validate){		//判断验证码是否正确
    			userRegesterManage = userService.findUserByNameAndPassword(email);
    			if(userRegesterManage == null){	//判断邮箱是否存在
    				//对密码进行加密
    				try {
						password = Md5Util.EncoderPwdByMd5(password);
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    				getModel(User.class).setSex("女").setSign("知识改变命运！").setPassword(password).setImageCode("default.jpg")
    				.setRoleName("会员").setRegisterDate(register_date)
    				.save();
    								
                	setAttr("errorMsg", "注册成功,请去登录。");
                	
                    render("regester.html");
                    return;
    			}else{
                	setAttr("errorMsg", "该邮箱已经存在,请重新输入。");
                    render("regester.html");
                    return;
    			}
//    		}else{
//            	setAttr("errorMsg", "验证码输入错误,请重新输入。");
//                render("regester.html");
//                return;
//    		}
    	}else{
        	setAttr("errorMsg", "两次密码不一致,请重新输入。");
            render("regester.html");
            return;
    	}
	}
	/**
	 * 前台根据用户的邮箱验证用户登录
	 */
	/*@SuppressWarnings("static-access")
	public void loginVerification(){
		setAttr("title", "用户登录");
		User userLoginManage ;
		//获取用户输入的账号和密码
    	String email  = getPara("email");
    	String password = getPara("password");
 	
    	//把密码进行Md5加密
    	try {
			password = Md5Util.EncoderPwdByMd5(password);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	//验证验证码的正确
    	boolean validate = validateCaptcha("imageCode");
    	//首先验证验证码的正确性
    	if(validate){
    		//从数据库中获取数据
    		userLoginManage = userService.findUserByNameAndPassword(email);
        	//验证用户名和密码是否正确
        	if(userLoginManage != null){
        		if("false".equals(userLoginManage.getStr("is_off"))){	//验证用户是否被禁用了
        			//System.out.println(userLoginManage);
        			//System.out.println("面膜："+userLoginManage.getStr("password"));
        			if(password.equals(userLoginManage.getStr("password"))){	//验证密码的正确性
        				// 将用户信息保存到缓存，用作超时判断
        				//userLoginManage.removeSensitiveInfo();  //移除密码

        				userLoginManage.removeSensitiveInfo();
        				long liveSeconds =  120 * 60;
        				long expireAt = System.currentTimeMillis() + (liveSeconds * 1000);
        				Session session = new Session();
        				String sessionId = StrKit.getRandomUUID();
        				
        				session.setId(sessionId);
        				session.setAccountId(userLoginManage.getUid());
        				session.setExpireAt(expireAt);
        				CacheKit.put(userService.loginAccountCacheName, sessionId, userLoginManage);
        				
        				String sessionIds = userLoginManage.getStr(userService.sessionIdName);
        				setCookie(userService.sessionIdName, sessionId, -1, true);
        				setAttr(userService.loginAccountCacheName, userLoginManage.get(userService.loginAccountCacheName));
        				
        				setSessionAttr("LoginUserCache",userLoginManage);
        				//setSessionUser(user); // 设置session
        				//System.out.println(getSessionAttr("LoginUserCache"));
        				
        				redirect("/user/userWelcome");
        			}else{
                    	setAttr("errorMsg", "邮箱或密码输入错误，请重新输入。");
                        render("login.html");
                        return;
        			}
        		}else{
                	setAttr("errorMsg", "对不起该用户被禁用了，请联系管理员解除。");
                    render("login.html");
                    return;
        		}	
        	}else{
            	setAttr("errorMsg", "该邮箱不存在,请重新输入。");
                render("login.html");
                return;
        	}
    	}else{
        	setAttr("errorMsg", "验证码输入错误,请重新输入。");
            render("login.html");
            return;
    	}
	}
	/**
	 * 用户注册验证
	 */
	/*@SuppressWarnings("null")
	public void regesterCheck(){
		setAttr("title", "用户注册");
		User userRegesterManage = new User();
    	String email  = getPara("user.email");
    	String username  = getPara("user.username");
    	String password = getPara("user.password");
    	String newPassword = getPara("newPassword");
    	String imageCode = getPara("imageCode");
    	
    	//注册时间
    	Date register_date = new Date();
    	
    	if(password.equals(newPassword)){		//判断两次密码是否一致
        	imageCode.toUpperCase();
        	boolean validate = MyCaptchaRender.validate(this, imageCode);
    		if(validate){		//判断验证码是否正确
    			userRegesterManage = userService.findUserByNameAndPassword(email);
    			if(userRegesterManage == null){	//判断邮箱是否存在
    				//对密码进行加密
    				try {
						password = Md5Util.EncoderPwdByMd5(password);
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    				getModel(User.class).setSex("女").setSign("知识改变命运！").setPassword(password).setImageCode("default.jpg")
    				.setRoleName("会员").setRegisterDate(register_date)
    				.save();
    								
                	setAttr("errorMsg", "注册成功,请去登录。");
                	
                    render("regester.html");
                    return;
    			}else{
                	setAttr("errorMsg", "该邮箱已经存在,请重新输入。");
                    render("regester.html");
                    return;
    			}
    		}else{
            	setAttr("errorMsg", "验证码输入错误,请重新输入。");
                render("regester.html");
                return;
    		}
    	}else{
        	setAttr("errorMsg", "两次密码不一致,请重新输入。");
            render("regester.html");
            return;
    	}
	}*/
	/**
	 * 用户找回密码验证
	 * @throws UnsupportedEncodingException 
	 * @throws NoSuchAlgorithmException 
	 */
	public void redmeCheck() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		setAttr("title", "找回密码");
		User user = new User();
    	String email  = getPara("email");
    	String imageCode = getPara("imageCode");
    	//邮件标题
    	String emailTitle = "拾光分享网密码找回邮件";
    	//邮件内容
    	String emailContent = "";
    	//验证码全部转换成大写的
    	imageCode.toUpperCase();
    	boolean validate = MyCaptchaRender.validate(this, imageCode);
    	if(validate){	//判断验证码是否正确
    		user = userService.findUserByNameAndPassword(email);
    		if(user != null){		//判断邮箱是否存在
    			//随机生成一个6位数的密码，后期可以用MD5密码，这里只做测试使用
        		String newNum = StringUtil.genSixRandomNum();
        		emailContent = "您在拾光分享网中的账号邮箱为"+ email + "重置了为密码为 ：" + newNum +"，如果不是您的操作，请忽视。";
        		//更新数据库中的密码
        		newNum = Md5Util.EncoderPwdByMd5(newNum);
        		userService.useEmailUpdatePassword(newNum,email);
        		try{
            		MailKit.send(email, Arrays.asList(email),emailTitle, emailContent);
                	setAttr("errorMsg", "邮箱发送成功，请注意查收。");
                	//System.out.println("成功");
                	render("redmePassword.html");
                    return; 
                }catch (Exception e){
                	e.printStackTrace();
                	setAttr("errorMsg", "邮箱发送失败，请联系管理员。");
                	render("redmePassword.html");
                    return; 
                }
    		}else{
            	setAttr("errorMsg", "邮箱不存在,请重新输入。");
                render("redmePassword.html");
                return;
    		}
    	}else{
        	setAttr("errorMsg", "验证码输入错误,请重新输入。");
            render("redmePassword.html");
            return;
    	}
	}
	/**
	 * 生成随机验证码
	 */
	@Clear
    public void getCaptcha(){
        //render(new MyCaptchaRender(60,35,4,true));
        //renderCaptcha();
    	renderCaptcha();
    }
    /**
     * 用户退出清除session
     */
    public void logout(){
		userService.logout(getCookie(userService.sessionIdName));
		removeCookie(UserService.sessionIdName);
		getSession().removeAttribute("LoginUserCache");
		redirect("/");
    }

}
